﻿using AutoMapper;
using ICSharpCode.TextEditor.Document;
using Newtonsoft.Json;
using Oplug.EntityFramework.RossLive;
using Oplug.CoolTower.Filters;
using Oplug.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;

namespace Oplug.CoolTower
{
    public partial class FormBAQ : MetroFramework.Forms.MetroForm
    {
        private DTO.SysConfig cfg;
        private DataSQL model;
        private Utilities Utility;
        public FormBAQ()
        {
            InitializeComponent();
        }
        [Description("模板维护窗口加载")]
        private void FormBAQ_Load(object sender, EventArgs e)
        {
            Utility = new Utilities();
            cfg = Utility.GetSysCfg();
            model = new DataSQL();
            this.Text += "-" + Utilities.CompName;
            LoadData();

            SQLEditor.ShowEOLMarkers = false;
            SQLEditor.ShowHRuler = false;
            SQLEditor.ShowInvalidLines = false;
            SQLEditor.ShowMatchingBracket = true;
            SQLEditor.ShowSpaces = false;
            SQLEditor.ShowTabs = false;
            SQLEditor.ShowVRuler = false;
            SQLEditor.AllowCaretBeyondEOL = false;
            SQLEditor.Encoding = Encoding.UTF8;

            string path = Application.StartupPath + "\\SyntaxModes";
            FileSyntaxModeProvider fsmp;
            if (System.IO.Directory.Exists(path))
            {
                fsmp = new FileSyntaxModeProvider(path);
                HighlightingManager.Manager.AddSyntaxModeFileProvider(fsmp);
                SQLEditor.SetHighlighting("TSQL");
            }
            RossGridViewM.Owner = this;
            RossGridViewM.OnInit();
        }

        private void LoadData()
        {
            using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
            {
                var resp = ObjServ.repository.GetAllList().Select(o => new { o.ID, o.ViewName, o.DisplayName,o.ViewType,o.Version }).ToList();
                dgv2.DataSource = resp;
                dgv2.Columns[0].Visible = false;
                dgv2.Columns[1].Visible = false;
                dgv2.Columns[2].HeaderCell.Value = "名称";
                dgv2.Columns[3].Visible = false;
                dgv2.Columns[4].Visible = true;
                dgv2.Columns[4].HeaderCell.Value = "版本号";
            }
        }
        [Description("新建模板")]
        private void toolNewSQL_Click(object sender, EventArgs e)
        {
            if (!MethodFilters.IsDeny(MethodBase.GetCurrentMethod().Name, Name, cfg.DBConn))
            {
                SQLEditor.Enabled = true;
                SQLEditor.Text = "";
                SQLEditor.Focus();
                tboxViewDisp.Text = "";
                tboxViewName.Text = "";
                model = new DataSQL();
            }
        }
        [Description("保存模板")]
        private void toolSave_Click(object sender, EventArgs e)
        {
            if (!MethodFilters.IsDeny(MethodBase.GetCurrentMethod().Name, Name, cfg.DBConn))
            {
                if(string.IsNullOrEmpty(SQLEditor.Text))
                {
                    Utilities.Message("模板数据源不能为空！", InfoType.Warning);
                    return;
                }
                using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
                {
                    string viewName = tboxViewName.Text;
                    string viewDispName = tboxViewDisp.Text;
                    string version = tboxVersion.Text;
                    if (!string.IsNullOrEmpty(viewName))
                    {
                        if (model.ID == 0)
                        {
                            var obj = ObjServ.repository.GetAllList(o => o.ViewName == viewName && o.DisplayName == viewDispName).FirstOrDefault();
                            if (obj != null)
                            {
                                Utilities.Message("模板" + viewName+ "已存在！", InfoType.Warning);
                            }
                            else
                            {
                                model.CreateTime = DateTime.Now;
                                model.CreateUser = Utilities.UserName;
                                model.SQLText = SQLEditor.Text;
                                model.ViewName = viewName;
                                model.DisplayName = viewDispName;
                                model.ViewType = "view";
                                model.Version = version;
                                ObjServ.repository.Insert(model);
                                LoadData();
                            }
                        }
                        else
                        {
                            model.ViewName = viewName;
                            model.DisplayName = viewDispName;
                            model.ViewType = "view";
                            model.Version = version;
                            model.SQLText = SQLEditor.Text;
                            ObjServ.repository.Update(model);
                            LoadData();
                        }
                    }
                }
            }
        }
        [Description("编辑模板")]
        private void toolEditSQL_Click(object sender, EventArgs e)
        {
            using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
            {
                long ID = long.Parse(dgv2.CurrentRow.Cells["ID"].Value.ToString());
                model = ObjServ.repository.Get(ID);
                SQLEditor.Enabled = true;
                SQLEditor.Text = model.SQLText;
                tboxViewDisp.Text = model.DisplayName;
                tboxViewName.Text = model.ViewName;
                tboxVersion.Text = model.Version;
            }
        }
        [Description("删除模板")]
        private void toolDelSQL_Click(object sender, EventArgs e)
        {
            if (!MethodFilters.IsDeny(MethodBase.GetCurrentMethod().Name, Name, cfg.DBConn))
            {
                string viewName = dgv2.CurrentRow.Cells["ViewName"].Value.ToString();
                if (MessageBox.Show("确定删除" + viewName + "！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
                    {
                        long ID = long.Parse(dgv2.CurrentRow.Cells["ID"].Value.ToString());
                        ObjServ.repository.Delete(ID);
                        LoadData();
                    }
                }
            }
        }
        [Description("执行模板")]
        private void toolBtn_Run_Click(object sender, EventArgs e)
        {
            if (!MethodFilters.IsDeny(MethodBase.GetCurrentMethod().Name, Name, Utilities.DefConn))
            {
                using (OplugLiveService ObjServ = new OplugLiveService(cfg.DBConn))
                {
                    try
                    {
                        var dt = Utility.SqlQuery(ObjServ.dbContext.Database, SQLEditor.Text);
                        RossGridViewM.DataSource = dt;
                        RossGridViewM.BindData();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void dgv2_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            toolEditSQL_Click(sender, e);
        }

        [Description("导出模板")]
        private void toolBtn_ExXML_Click(object sender, EventArgs e)
        {
            if (MethodFilters.IsDeny(MethodBase.GetCurrentMethod().Name, Name, Utilities.DefConn))
            {
                return;
            }
            using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
            {
                var resp = ObjServ.repository.GetAllList();
                var jsons = JsonConvert.SerializeObject(resp);

                XmlDictionaryReader reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(jsons), XmlDictionaryReaderQuotas.Max);
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);

                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.Filter = "XML files(*.xml)|*.xml|All files(*.*)|*.*";
                saveFile.RestoreDirectory = true;
                saveFile.FileName = "View" + DateTime.Now.ToString("yyMMddhhmmssfff");
                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    doc.Save(saveFile.FileName);
                    Utilities.Message("导出成功！", InfoType.Information);
                }               
            }
        }
        [Description("导入模板")]
        private async void toolBtn_ImXML_Click(object sender, EventArgs e)
        {
            if (MethodFilters.IsDeny("toolBtn_ImXML_Click", Name, Utilities.DefConn))
            {
                return;
            }
            XmlDocument xmldoc = new XmlDocument();
            OpenFileDialog file = new OpenFileDialog();
            file.Filter = "XML files(*.xml)|*.xml";

            DTO.DataSQLRoot obj = new DTO.DataSQLRoot();
            if (file.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(file.FileName);
                XmlSerializer serializer = new XmlSerializer(typeof(DTO.DataSQLRoot));
               obj = serializer.Deserialize(sr) as DTO.DataSQLRoot;
            }

            if (obj != null)
            {
                SQLEditor.Text = "";
                using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
                {
                    var lists = Mapper.Map<List<DataSQL>>(obj.items);
                    if (lists != null)
                    {
                        foreach (var item in lists)
                        {
                            await Task.Run(() =>
                            {
                                var vobj = ObjServ.repository.GetAllList(o => o.ViewName == item.ViewName).FirstOrDefault();
                                if (vobj != null)
                                {
                                    vobj.SQLText = item.SQLText;
                                    vobj.Version = item.Version;
                                    ObjServ.repository.Update(vobj);
                                }
                                else
                                {
                                    item.ID = 0;
                                    ObjServ.repository.Insert(item);
                                }
                            });
                            SQLEditor.Text += DateTime.Now.ToString() + " " + item.ViewName + " import successful. \r\n";
                        }
                        Utilities.Message("导入成功！", InfoType.Information);
                        LoadData();
                    }
                }                
            }

        }

        private void tboxViewName_Leave(object sender, EventArgs e)
        {
            if (model != null)
            {
                if (!string.IsNullOrEmpty(tboxViewName.Text))
                {
                    using (DataSQLService ObjServ = new DataSQLService(Utilities.DefConn))
                    {
                        var obj = ObjServ.repository.GetAllList(o => o.ViewName == tboxViewName.Text).FirstOrDefault();
                        if (obj != null)
                        {
                            tboxVersion.Text = obj.Version;
                            tboxViewDisp.Text = obj.DisplayName;
                            SQLEditor.Text = obj.SQLText;
                            model = obj;
                        }
                    }
                }
            }
        }

        private void OpenReportTmp_Click(object sender, EventArgs e)
        {
            //点击弹出对话框
            OpenFileDialog openFileDialog = new OpenFileDialog();

            //设置对话框的标题
            openFileDialog.Title = "请选择要打开的模板";

            //设置对话框可以多选
            openFileDialog.Multiselect = false;

            //设置对话框的初始目录
            openFileDialog.InitialDirectory = Application.StartupPath + @"\Tmp";

            //设置对话框的文件类型
            openFileDialog.Filter = "报表文件|*.frx|所有文件|*.*";

            //展示对话框
            openFileDialog.ShowDialog();

            ////获得在打开的对话框中选中文件的路径
            string path = openFileDialog.FileName;
            

            if (path == "")
            {
                return;
            }
            else
            {
                var trueName = path.Substring(path.LastIndexOf('\\')+1).Replace(".frx", "");
                tboxViewName.Text = trueName;
            }
            
        }

        private void buttonDesign_Click(object sender, EventArgs e)
        {
            if (model == null)
            {
                Utilities.Message("请选择报表！");
                return;
            }
            try
            {
                FastReport.Report report = new FastReport.Report();
                string filename = Application.StartupPath + @"\Tmp\" + model.ViewName + ".frx";
                report.Load(filename);
                using (OplugLiveService Serv = new OplugLiveService(cfg.DBConn))
                {
                    DataTable dt = Utility.SqlQuery(Serv.dbContext.Database, model.SQLText);
                    DataSet data = new DataSet();
                    dt.TableName = "DataTable";
                    data.Tables.Add(dt);
                    report.RegisterData(data);
                    var ds = report.GetDataSource("DataTable");
                    ds.Enabled = true;
                    report.Design();
                }
            }
            catch(Exception ex)
            {
                Utilities.Message(ex.Message, InfoType.Error);
            }
        }
    }
}
